package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Tag(name = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Operation(summary = "创建帖子")
    @PostMapping("/create")
    public AppResult createArticle(HttpServletRequest request,
                                    @Param("板块id") @RequestParam("boardId") @NonNull Long boardId,
                                   @Param("帖子标题") @RequestParam("title") @NonNull String title,
                                   @Param("帖子内容") @RequestParam("content") @NonNull String content) {

        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 版块的校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);
        articleService.createArticle(article);
        return AppResult.success();
    }

    @Operation(summary = "获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (@Param("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {

        List<Article> articles;
        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if (articles == null) {
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }

    @Operation(summary = "获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @Param("帖子id") @RequestParam("id") @NonNull Long id) {
        // 从session中获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用Service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(Objects.equals(user.getId(), article.getUserId())){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @Operation(summary = "修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Param("帖子Id") @RequestParam("id") @NonNull Long id,
                            @Param("帖子标题") @RequestParam("title") @NonNull String title,
                            @Param("帖子内容") @RequestParam("content") @NonNull String content) {
        // 从session中获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (!Objects.equals(user.getId(), article.getUserId())){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        // 判断帖子是否被删除
        if(article.getState() == 1 || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 调用Service
        articleService.modify(id, title, content);
        log.info("修改成功 Article id:{},User id:{}",id,user.getId());
        return AppResult.success();
    }

    @Operation(summary = "点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpById(HttpServletRequest request,
            @Param("帖子id") @RequestParam("id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用Service
        articleService.thumbsUpById(id);
        return AppResult.success();
    }


    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
            @Param("帖子id") @RequestParam("id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (!Objects.equals(user.getId(), article.getUserId())){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用Service
        articleService.deleteById(id);
        return AppResult.success();
    }

    @Operation(summary = "获取用户发布的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
            @Param("用户id") @RequestParam(value = "userId",required = false) Long userId) {
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        log.info("获取用户发布的帖子列表成功 User id:{}",userId);
        return AppResult.success(articles);
    }
}
